<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>


                    <el-date-picker style=" width: 240px;" v-model="data_time" @change="datetime_btn" type="daterange"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />

                    <el-select style="margin-left: 20px;width:180px" v-model="find_data.plateNum" placeholder="车牌"
                        clearable>
                        <el-option v-for="item in findCarCombo_list" :key="item.id" :label="item.plate_num"
                            :value="item.plate_num" />
                    </el-select>



                    <el-select style="margin-left: 20px;width:180px" v-model="find_data.driverUserId" placeholder="驾驶员"
                        clearable>
                        <el-option v-for="item in getDriverCombo_list" :key="item.id" :label="item.realName"
                            :value="item.ftUserId" />
                    </el-select>

                    <el-select style="margin-left: 20px;width:180px" v-model="find_data.abnormalityType"
                        placeholder="异常类型" clearable>
                        <el-option label="违章" value="0" />
                        <el-option label="事故" value="1" />
                    </el-select>

                    <el-select multiple collapse-tags style="margin-left: 20px;width:180px"
                        v-model="find_data.abnormalityStatus" placeholder="异常状态" clearable>
                        <el-option label="待驾驶员处理" value="WAIT_DRIVER_OPER" />
                        <el-option label="待管理员审核" value="WAIT_MANAGER_CHECK" />
                        <el-option label="审核通过" value="CHECKED" />
                        <el-option label="审核不通过" value="REFUESD" />
                    </el-select>

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="Plus">新增</el-button>
                    <el-button @click="up_btn" type="primary" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="primary" icon="CircleCloseFilled">删除</el-button>




                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="67vh"
                    ref="multipleTableRef" :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'abnormalityType'" #="{ row, column, $index }">
                                <span>{{ row.abnormalityType == 0 ? '违章' : '事故' }}</span>
                            </template>
                            <template v-if="item.field == 'leaveTypeName'" #="{ row, column, $index }">
                                <span :style='row.abnormalityStatus == "WAIT_MANAGER_CHECK" ? "color:red" : ""'>{{
                                    row.abnormalityStatus == 'WAIT_DRIVER_OPER' ? '待驾驶员处理' : row.abnormalityStatus
                                        == 'WAIT_MANAGER_CHECK' ? '待管理员审核' : row.abnormalityStatus
                                            == 'CHECKED' ? '审核通过' : row.abnormalityStatus == 'REFUESD' ? '审核不通过' : '' }}</span>
                            </template>
                            <template v-if="item.field == 'driverUserId'" #="{ row, column, $index }">
                                <span>{{ row.driverInfo }}</span>
                            </template>
                            <template v-if="item.field == 'abnormalityUrl'" #="{ row, column, $index }">
                                <template v-if="row.abnormalityUrl">
                                    <el-image v-for="item in row.abnormalityUrl.split(',')"
                                        style="width: 40px; height: 40px" :preview-teleported="true"
                                        :preview-src-list="[ImageUrl + item]" :src="item ? ImageUrl + item : ''"
                                        fit="cover">
                                        <template #error>
                                            <div>
                                                <el-icon style="width: 95px; height: 95px"><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </template>


                            </template>
                            <template v-if="item.field == 'proveUrl'" #="{ row, column, $index }">
                                <template v-if="row.proveUrl">
                                    <el-image v-for="item in row.proveUrl.split(',')" style="width: 40px; height: 40px"
                                        :preview-teleported="true" :preview-src-list="[ImageUrl + item]"
                                        :src="item ? ImageUrl + item : ''" fit="cover">
                                        <template #error>
                                            <div>
                                                <el-icon style="width: 95px; height: 95px"><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </template>


                            </template>
                        </el-table-column>

                    </template>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template #default="{ row, column, $index }">

                            <el-button type="primary" size="small" @click="release_btn(row)">操作</el-button>

                        </template>
                    </el-table-column>

                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="80%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="130px" label-suffix="：">

                <div style="display: flex;">
                    <el-form-item label="类型">
                        <el-select @change='abnormalityType_change' style="width:100px"
                            v-model="add_data.abnormalityType" placeholder="异常类型" clearable>
                            <el-option label="违章" value="0" />
                            <el-option label="事故" value="1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车牌号">
                        <el-select style="width:120px" @change="vehicleIdentifyNum_change" v-model="add_data.plateNum"
                            placeholder="车牌" clearable>
                            <el-option v-for="item in findCarCombo_list" :key="item.id" :label="item.plate_num"
                                :value="item.plate_num" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="车架号" v-if="add_data.plateNum != '川A91E5J'">
                        <div style="width:180px"> {{ vehicleIdentifyNum }}</div>
                    </el-form-item>
                    <el-form-item label="驾驶员">
                        <el-select style="width:130px" v-model="add_data.driverUserId" placeholder="驾驶员" clearable>
                            <el-option v-for="item in getDriverCombo_list" :key="item.id" :label="item.realName"
                                :value="item.ftUserId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="异常发生时间">

                        <el-date-picker v-model="add_data.abnormalityTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="异常发生时间" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="图片">
                        <div style="display: flex;    justify-content: space-evenly;">
                            <el-upload v-model:file-list="adupRewardPunish_rawFile_list2" style="margin-top: 10px;"
                                class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                                :data="{ ftype: ftype, files: rawFile_list }" list-type="picture-card"
                                :on-remove="handleRemove" :on-preview="handlePictureCardPreview"
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">

                                <el-icon class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                            <el-dialog v-model="dialogVisible">
                                <div style="width:60vh;height:60vh;margin:auto;">
                                    <img style="width:60vh;height:60vh;margin:auto;" :src="ImageUrl + dialogImageUrl"
                                        alt="Preview Image" />
                                </div>
                            </el-dialog>
                        </div>
                    </el-form-item>
                </div>
                <el-form-item label="备注">

                    <el-input show-word-limit :autosize="{ minRows: 3, maxRows: 4 }" maxlength="200" type="textarea"
                        v-model="add_data.note" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="驾驶证扣分">
                        <el-input v-model="add_data.subDrivePoint" style="width: 160px" type="number"
                            placeholder="驾驶证扣分" />
                    </el-form-item>
                    <el-form-item label="买分金额">
                        <el-input v-model="add_data.buyPointPrice" style="width: 120px" type="number"
                            placeholder="买分金额" />
                    </el-form-item>
                    <el-form-item style="margin-left: 20px;" label="驾驶员处罚金额">
                        <el-input v-model="add_data.driverPunishPrice" style="width: 160px" type="number"
                            placeholder="驾驶员处罚金额" />
                    </el-form-item>
                    <el-form-item style="margin-left: 20px;" label="公司赔偿金额">
                        <el-input v-model="add_data.indemnityPrice" style="width: 160px" type="number"
                            placeholder="公司赔偿金额" />
                    </el-form-item>
                    <el-form-item style="margin-left: 20px;" label="驾驶员承担金额">
                        <el-input v-model="add_data.driverIndemnityPrice" style="width: 160px" type="number"
                            placeholder="驾驶员承担金额" />
                    </el-form-item>

                </div>


            </el-form>


            <el-button @click="ok_btn" style="margin-left:70vw" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 审核通过 -->

        <el-dialog style="margin-top:5vh" v-model="release_off" title="驾驶员上传的处理截图" width="40%"
            :close-on-click-modal='false'>
            <el-form :model="release_data" label-width="130px" label-suffix="：">
                <el-form-item label="违章截图">
                    <div class="demo-image__preview" v-for="item in proveUrl_rawFile_list">
                        <el-image style="width: 100px; height: 100px" :src="ImageUrl + item" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2" :preview-src-list="[ImageUrl + item]" :initial-index="4"
                            fit="cover" />


                    </div>
                </el-form-item>
                <el-form-item label="备注">
                    {{ release_data.note }}
                </el-form-item>
                <div style="display: flex;justify-content: space-around;font-weight:700">
                    <div>驾驶证扣分：{{ release_data3.subDrivePoint }}元</div>
                    <div>买分金额：{{ release_data3.buyPointPrice }}元</div>
                    <div>驾驶员处罚金额：{{ release_data3.driverPunishPrice }}元</div>
                    <div>公司赔偿金额：{{ release_data3.indemnityPrice }}元</div>
                    <div>驾驶员承担金额：{{ release_data3.driverIndemnityPrice }}元</div>
                </div>
            </el-form>



            <el-divider><span style="color: red;">审核操作</span></el-divider>

            <div style="margin-top: 20px;">
                <el-form :model="release_data2" label-width="130px" label-suffix="：">
                    <div style="display: flex;">
                        <!-- <el-form-item label="图片">
                            <div style="display: flex;    justify-content: space-evenly;">
                                <el-upload v-model:file-list="adupRewardPunish_rawFile_list4" style="margin-top: 10px;"
                                    class="avatar-uploader" :action="ImageUrl_upload" :headers="{ token: GET_TOKEN() }"
                                    :data="{ ftype: ftype, files: rawFile_list2 }" list-type="picture-card"
                                    :on-remove="handleRemove2" :on-preview="handlePictureCardPreview2"
                                    :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2">

                                    <el-icon class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>

                                <el-dialog style="margin-top: 5vh;" v-model="dialogVisible2">
                                    <div
                                        style="width:80vh;height:80vh;margin:auto;display: flex; justify-content: center;">
                              
                                        <el-image style="width:80vw;height:80vh;" :src="ImageUrl + dialogImageUrl2" />
                                    </div>
                                </el-dialog>
                            </div>
                           
                        </el-form-item> -->
                        <el-form-item label="驾驶员上传图片">
                            <div class="demo-image__preview" v-for="item in adupRewardPunish_rawFile_list3">
                                <el-image style="width: 100px; height: 100px" :src="ImageUrl + item" :zoom-rate="1.2"
                                    :max-scale="7" :min-scale="0.2" :preview-src-list="[ImageUrl + item]"
                                    :initial-index="4" fit="cover" />


                            </div>
                        </el-form-item>
                    </div>
                    <el-form-item label="驾驶员备注">

                        <el-input disabled show-word-limit :autosize="{ minRows: 3, maxRows: 4 }" maxlength="200"
                            type="textarea" v-model="release_data2.proveRemark" />
                    </el-form-item>
                </el-form>

            </div>

            <div style="display: flex;margin-left:27vw;"
                v-if="release_data.abnormalityStatus != 'REFUESD' && release_data.abnormalityStatus != 'CHECKED'">
                <el-button @click="checkLeave_ok_btn('CHECKED')" type="primary">审核通过</el-button>
                <el-button @click="checkLeave_ok_btn('REFUESD')" type="warning">审核不通过</el-button>
            </div>


        </el-dialog>

    </div>
</template>

<script setup>
import {
    line2treeData, findP2CArr, setFmArr, importCusCheckInData, ImageUrl_upload, ImageUrl,

} from '@/utils/common.js'
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, findVehicleAbnormalityList, findCarCombo, getDriverCombo, adupVehicleAbnormality,
    getFileType, delVehicleAbnormality, getVehicleAbnormalityById, checkAbnormality, findTrusteeshipMeCombo

} from '@/api/human_resources_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'


import CircularJSON from 'circular-json'

onMounted(async () => {


    getPrivateSetList({
        find: '违章与事故',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    findTrusteeshipMeCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        companyName: '',
    }).then(res => {
        let luser = JSON.parse(localStorage.getItem("luser"))
        let luser_companyNum = luser.companyNum
        let companyNums = [luser_companyNum]
        if (res.data) {
            for (let i = 0; i < res.data.length; i++) {
                console.log(res.data[i].companyNum)
                companyNums.push(res.data[i].companyNum)
            }
        }
        findCarCombo({
            page: {
                pageNum: 1,
                pageSize: 999,
            },
            plateNum: '',
            companyNums: companyNums,
        }).then(res => {

            findCarCombo_list.value = res.data.list
        })
    })

    getFileType({}).then(res => {

    })

    getDriverCombo({
        page: {
            pageNum: 1,
            pageSize: 999,
        },
        plateNum: '',
    }).then(res => {
        getDriverCombo_list.value = res.data
    })



    // data_time.value = [new_day(), to_day()]
    // find_data.stime = new_day()
    // find_data.etime = to_day()
    await list_api()

})
const vehicleIdentifyNum = ref('')
const vehicleIdentifyNum_change = (e) => {
    vehicleIdentifyNum.value = ''
    for (let i = 0; i < findCarCombo_list.value.length; i++) {
        if (e == findCarCombo_list.value[i].plate_num) {
            vehicleIdentifyNum.value = findCarCombo_list.value[i].vehicle_identify_num ? findCarCombo_list.value[i].vehicle_identify_num : '暂无'
        }
    }
}
const new_day = () => {
    let currentDate = new Date();
    let firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    let lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

    function formatDate(date) {
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0');
        let day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    let formattedFirstDay = formatDate(firstDay);
    let formattedLastDay = formatDate(lastDay);
    return formattedFirstDay

}
const to_day = () => {
    let currentDate = new Date();
    let firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    let lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

    function formatDate(date) {
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0');
        let day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    let formattedFirstDay = formatDate(firstDay);
    let formattedLastDay = formatDate(lastDay);
    return formattedLastDay
}
const data_time = ref('')
const datetime_btn = (x, y) => {
    if (x) {
        data_time.value = x
        find_data.stime = data_time.value[0]
        find_data.etime = data_time.value[1]
    } else {
        find_data.stime = ''
        find_data.etime = ''
    }

}
const findCarCombo_list = ref([])

const getDriverCombo_list = ref([])
//#region 操作
const release_off = ref(false)
const release_data = ref({
    id: '',
    abnormalityUrl: '',
    proveRemark: '',
    abnormalityStatus: '',
    note: '',
})
const release_data2 = ref({
    id: '',
    abnormalityUrl: '',
    proveRemark: '',
})
const proveUrl_rawFile_list = ref([])
const release_data3 = ref({})
const release_btn = (e) => {
    getVehicleAbnormalityById({
        id: e.id,
    }).then(res => {
        release_data3.value = res.data
        release_data.value.proveRemark = res.data.proveRemark
        release_data.value.id = res.data.id
        release_data.value.abnormalityStatus = res.data.abnormalityStatus
        // console.log(release_data.value, 'release_data.value')
        release_data.value.note = res.data.note
        if (res.data.abnormalityUrl) {
            proveUrl_rawFile_list.value = res.data.abnormalityUrl.split(',')
        } else {
            proveUrl_rawFile_list.value = []
        }
        adupRewardPunish_rawFile_list3.value = []
        adupRewardPunish_rawFile_list4.value = []
        rawFile_list2.value = []

        release_data2.value.proveRemark = res.data.proveRemark

        adupRewardPunish_rawFile_list3.value = res.data.proveUrl ? res.data.proveUrl.split(',') : ''
        if (adupRewardPunish_rawFile_list3.value.length > 0) {
            for (let i = 0; i < adupRewardPunish_rawFile_list3.value.length; i++) {
                let data = {
                    name: i,
                    url: ImageUrl + adupRewardPunish_rawFile_list3.value[i]
                }
                adupRewardPunish_rawFile_list4.value.push(data)
            }
        } else {
            adupRewardPunish_rawFile_list4.value = []
        }
    })

    release_off.value = true
}
const checkLeave_ok_btn = (e) => {

    // let ps = {
    //     id: release_data.value.id,
    //     abnormalityStatus: e,
    //     proveUrl: adupRewardPunish_rawFile_list3.value ? adupRewardPunish_rawFile_list3.value.join(',') : '',
    //     proveRemark: release_data2.value.proveRemark,
    // }


    ElMessageBox.confirm(
        '确认操作?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            let ps = {
                id: release_data.value.id,
                abnormalityStatus: e,
                proveUrl: '',
                proveRemark: '',
            }
            // return console.log(ps)
            checkAbnormality(ps).then(res => {
                if (res.code == 1) {
                    release_off.value = false
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })


}
//#endregion
//#region 表格数据处理
const table_data_list = reactive([
    { label: '类型', field: 'abnormalityType', width: 100, off: true },
    { label: '违章时间', field: 'abnormalityTime', width: 200, off: true },
    { label: '车牌', field: 'plateNum', width: 150, off: true },
    { label: '车架号', field: 'vehicleIdentifyNum', width: 150, off: true },
    { label: '驾驶员', field: 'driverUserId', width: 180, off: true },
    { label: '扣分', field: 'subDrivePoint', width: 80, off: true },
    { label: '买分金额', field: 'buyPointPrice', width: 80, off: true },

    { label: '驾驶员处罚金额', field: 'driverPunishPrice', width: 130, off: true },
    { label: '公司赔偿金额', field: 'indemnityPrice', width: 130, off: true },
    { label: '驾驶员承担金额', field: 'driverIndemnityPrice', width: 130, off: true },
    { label: '处理结果', field: 'leaveTypeName', width: 120, off: true },
    { label: '备注', field: 'note', width: 320, off: true },
    { label: '异常图片', field: 'abnormalityUrl', width: 180, off: true },
    { label: '处理异常图片', field: 'proveUrl', width: 180, off: true },
    { label: '添加时间', field: 'addTime', width: 180, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '违章与事故',
        tbNum: "violations_and_accidents",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    driverUserId: '',
    stime: '',
    etime: '',
    plateNum: "",
    abnormalityType: "",
    abnormalityStatus: ['WAIT_MANAGER_CHECK', 'WAIT_DRIVER_OPER'],
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {
    let ps = {
        page: {
            pageNum: find_data.page.pageNum,
            pageSize: find_data.page.pageSize,
        },
        driverUserId: find_data.driverUserId,
        stime: find_data.stime,
        etime: find_data.etime,
        plateNum: find_data.plateNum,
        abnormalityType: find_data.abnormalityType,
        abnormalityStatus: find_data.abnormalityStatus.join(',')
    }

    findVehicleAbnormalityList(ps).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const ftype = ref('CAR_VIOLATION_IMG')
const abnormalityType_change = (e) => {
    console.log(e)
    if (e == 0) {
        ftype.value == 'CAR_VIOLATION_IMG'
    } else {

        ftype.value == 'CAR_ACCIDENT_IMG'
    }
}
const rawFile_list = ref([])
const rawFile_list2 = ref([])
const adupRewardPunish_rawFile_list = ref([])
const adupRewardPunish_rawFile_list2 = ref([])
const adupRewardPunish_rawFile_list3 = ref([])
const adupRewardPunish_rawFile_list4 = ref([])
const handleRemove = (uploadFile, uploadFiles) => {
    let url_data = uploadFile.response.data.file.url

    for (let i = 0; i < adupRewardPunish_rawFile_list.value.length; i++) {
        if (adupRewardPunish_rawFile_list.value[i] == url_data) {
            adupRewardPunish_rawFile_list.value.splice(i, 1);
        }
    }
}
const handleRemove2 = (uploadFile, uploadFiles) => {
    let url_data = uploadFile.response.data.file.url

    for (let i = 0; i < adupRewardPunish_rawFile_list3.value.length; i++) {
        if (adupRewardPunish_rawFile_list3.value[i] == url_data) {
            adupRewardPunish_rawFile_list3.value.splice(i, 1);
        }
    }
}

const handleAvatarSuccess = (response, uploadFile) => {

    adupRewardPunish_rawFile_list.value.push(response.data.file.url)

}
const handleAvatarSuccess2 = (response, uploadFile) => {

    adupRewardPunish_rawFile_list3.value.push(response.data.file.url)

}

const beforeAvatarUpload = (rawFile) => {
    rawFile_list.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list.value.push(rawFile)
    return true

}

const beforeAvatarUpload2 = (rawFile) => {
    rawFile_list2.value = []
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('图片大小不能大于5M!')
            return false
        }
    } else {
        ElMessage.error('请上传图片!')
        return false
    }

    rawFile_list2.value.push(rawFile)
    return true

}



const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const dialogImageUrl2 = ref('')
const dialogVisible2 = ref(false)
const handlePictureCardPreview = (uploadFile) => {
    console.log(uploadFile)
    if (uploadFile.response) {
        dialogImageUrl.value = uploadFile.response.data.file.url
    } else {


        console.log(uploadFile.url, uploadFile.url.split('https://cba360.com')[1])
        dialogImageUrl.value = uploadFile.url.split('https://cba360.com')[1]
    }

    dialogVisible.value = true
}
const handlePictureCardPreview2 = (uploadFile) => {
    if (uploadFile.response) {
        dialogImageUrl2.value = uploadFile.response.data.file.url
    } else {


        dialogImageUrl2.value = uploadFile.url.split('https://cba360.com')[1]
    }

    dialogVisible2.value = true
}

const add_off = ref(false)
const title = ref('新增违章与事故')

const add_data = reactive({
    id: '',
    abnormalityTime: '',
    abnormalityType: "0",
    abnormalityUrl: "",
    driverIndemnityPrice: "",
    driverPunishPrice: "",
    driverUserId: '',
    indemnityPrice: '',
    note: '',
    plateNum: '',
    subDrivePoint: '',
    buyPointPrice: '',
})

const add_btn = () => {
    title.value = '新增违章与事故'
    add_data.id = ''
    add_data.abnormalityTime = ''
    add_data.abnormalityType = '0'
    add_data.abnormalityUrl = ''
    add_data.driverIndemnityPrice = ''
    add_data.driverPunishPrice = ''
    add_data.driverUserId = ''
    add_data.indemnityPrice = ''
    add_data.note = ''
    add_data.plateNum = ''
    add_data.subDrivePoint = ''
    add_data.buyPointPrice = ''

    adupRewardPunish_rawFile_list.value = []
    adupRewardPunish_rawFile_list2.value = []
    rawFile_list.value = []
    add_off.value = true





}


//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    title.value = '修改违章与事故'
    adupRewardPunish_rawFile_list.value = []
    adupRewardPunish_rawFile_list2.value = []
    rawFile_list.value = []
    add_data.id = table_list.value[0].id
    add_data.abnormalityTime = table_list.value[0].abnormalityTime
    add_data.abnormalityType = String(table_list.value[0].abnormalityType)
    add_data.abnormalityUrl = table_list.value[0].abnormalityUrl
    add_data.driverIndemnityPrice = table_list.value[0].driverIndemnityPrice
    add_data.driverPunishPrice = table_list.value[0].driverPunishPrice
    add_data.driverUserId = table_list.value[0].driverUserId
    add_data.indemnityPrice = table_list.value[0].indemnityPrice
    add_data.note = table_list.value[0].note
    add_data.plateNum = table_list.value[0].plateNum
    add_data.subDrivePoint = table_list.value[0].subDrivePoint
    add_data.buyPointPrice = table_list.value[0].buyPointPrice
    adupRewardPunish_rawFile_list.value = table_list.value[0].abnormalityUrl ? table_list.value[0].abnormalityUrl.split(',') : ''
    if (adupRewardPunish_rawFile_list.value.length > 0) {
        for (let i = 0; i < adupRewardPunish_rawFile_list.value.length; i++) {
            let data = {
                name: i,
                url: ImageUrl + adupRewardPunish_rawFile_list.value[i]
            }
            adupRewardPunish_rawFile_list2.value.push(data)
        }
    } else {
        adupRewardPunish_rawFile_list2.value = []
    }
    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {

    ElMessageBox.confirm(
        '确认提交?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            add_data.abnormalityUrl = adupRewardPunish_rawFile_list.value.join(',')
            if (title.value == '新增违章与事故') {



                adupVehicleAbnormality(add_data).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
                list_api()
            } else {
                adupVehicleAbnormality(add_data).then(res => {
                    if (res.code == 1) {
                        list_api()
                        add_off.value = false
                        return ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        return ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
                })
                list_api()
            }
        })
        .catch((e) => {


        })







}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delVehicleAbnormality({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    list_api()
}
//#endregion


</script>

<style scoped lang='scss'></style>

<style>
.avatar-uploader .avatar {
    width: 200px;
    height: 200px;
    display: block;
}


.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
}

.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
